package com.example.mybatisannotation.service.impl;

import com.example.mybatisannotation.entity.Student;
import com.example.mybatisannotation.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StuServiceImpl implements StuService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int create(Student stu) {
        String strSql ="insert into tb_student (id,no, name, sex, phone, qq) values (?,?,?,?,?,?)";
        return jdbcTemplate.update(strSql,stu.getId(),stu.getNo(),stu.getName(),stu.getSex(),stu.getPhone(),stu.getQq());
    }
    @Override
    public List<Student> getByName(String name){
        String strSql="select * from tb_student where name like CONCAT('%',?,'%')";
        return jdbcTemplate.query(strSql,new BeanPropertyRowMapper<>(Student.class),name);
    }
    @Override
    public Student getByID(Integer id){
        String strsql="delete from tb_student where id=?";
        Student stu = jdbcTemplate.queryForObject(strsql,new BeanPropertyRowMapper<>(Student.class),
                new Object[] {id});
        return stu;
    }

    @Override
    public int deleteById(Integer id){
        String strsql="delete from tb_student where id=?";
        return jdbcTemplate.update(strsql,id);
    }

    @Override
    public List<Student> getAllStudents() {
        String strsql="select * from tb_student";
        return jdbcTemplate.query(strsql,new BeanPropertyRowMapper< >(Student.class));
    }

    @Override
    public int updateStu(Student stu) {
        String strsql="update tb_student set no=?,name=?,sex=?,"+"phone=?,qq=? where id=?";
        Object []argus ={stu.getNo(),stu.getName(),stu.getSex(),stu.getPhone(),stu.getQq(),stu.getId()};
        return jdbcTemplate.update(strsql,argus);
    }
}
